package com.mall.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.mall.common.To.mq.OrderTo;
import com.mall.common.To.mq.StockLockedDetail;
import com.mall.common.To.mq.StockLockedTO;
import com.mall.common.utils.R;
import com.mall.mall.ware.entity.WareOrderTaskDetailEntity;
import com.mall.mall.ware.entity.WareOrderTaskEntity;
import com.mall.mall.ware.exception.NoStockException;
import com.mall.mall.ware.feign.OrderFeignService;
import com.mall.mall.ware.feign.ProductFeignService;
import com.mall.common.To.SkuHasStockVo;
import com.mall.mall.ware.service.WareOrderTaskDetailService;
import com.mall.mall.ware.service.WareOrderTaskService;
import com.mall.mall.ware.vo.LockStockResultVo;
import com.mall.mall.ware.vo.OrderItemVO;
import com.mall.mall.ware.vo.OrderVO;
import com.mall.mall.ware.vo.WareSkuLockVO;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.mall.ware.dao.WareSkuDao;
import com.mall.mall.ware.entity.WareSkuEntity;
import com.mall.mall.ware.service.WareSkuService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    WareOrderTaskService wareOrderTaskService;

    @Autowired
    OrderFeignService orderFeignService;

    @Autowired
    WareOrderTaskDetailService wareOrderTaskDetailService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private void unLockStock(Long skuId, Long wareId, Integer num, Long taskDetailId){
        wareSkuDao.unlockStock(skuId, wareId, num);
        WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
        wareOrderTaskDetailEntity.setId(taskDetailId);
        wareOrderTaskDetailEntity.setLockStatus(0);
        wareOrderTaskDetailService.updateById(wareOrderTaskDetailEntity);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
        String skuId = (String) params.get("skuId");
        if (!StringUtils.isEmpty(skuId)){
            wrapper.eq("sku_id", skuId);
        }

        String wareId = (String) params.get("wareId");
        if (!StringUtils.isEmpty(wareId)){
            wrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        //1、判断如果还没有这个库存记录，则进行新增
        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(new QueryWrapper<WareSkuEntity>().eq("sku_id", skuId).eq("ware_id", wareId));
        if (CollectionUtils.isEmpty(wareSkuEntities)){
            WareSkuEntity wareSkuEntity = new WareSkuEntity();
            wareSkuEntity.setSkuId(skuId);
            wareSkuEntity.setWareId(wareId);
            wareSkuEntity.setStock(skuNum);
            wareSkuEntity.setStockLocked(0);
            //远程查询 sku 的名字
            try{
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0){
                    Map<String, Object> data  = (Map<String, Object>) info.get("skuInfo");
                    wareSkuEntity.setSkuName((String) data.get("skuName"));
                }
            }catch (Exception e){

            }

            wareSkuDao.insert(wareSkuEntity);
        }else {
            wareSkuDao.addStock(skuId, wareId, skuNum);
        }
    }

    @Override
    public List<SkuHasStockVo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockVo> collect = skuIds.stream().map(item -> {
            SkuHasStockVo skuHasStockVo = new SkuHasStockVo();
            Long count = this.baseMapper.getSkuStock(item);
            skuHasStockVo.setHasStock(count ==  null ? false : count > 0);
            skuHasStockVo.setSkuId(item);
            return skuHasStockVo;
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 为某个订单锁定库存
     * @param vo
     * @return
     */
    @Transactional
    @Override
    public Boolean orderLockStock(WareSkuLockVO vo) {
        // 保存库存工作单的详情
        WareOrderTaskEntity wareOrderTaskEntity = new WareOrderTaskEntity();
        wareOrderTaskEntity.setOrderSn(vo.getOrderSn());
        wareOrderTaskService.save(wareOrderTaskEntity);

        // 1、按照下单的收获地址，找到一个就近仓库，锁定库存
        List<OrderItemVO> locks = vo.getLocks();

        List<SkuWareHasStock> collect = locks.stream().map(item -> {
            Long skuId = item.getSkuId();
            SkuWareHasStock skuWareHasStock = new SkuWareHasStock();
            skuWareHasStock.setSkuId(skuId);
            skuWareHasStock.setNum(item.getCount());
            // 查询商品在哪里有库存
            List<Long> wareIds = wareSkuDao.listWareIdHasSkuStock(skuId);
            skuWareHasStock.setWareId(wareIds);
            return skuWareHasStock;
        }).collect(Collectors.toList());

        // 2、锁定库存
        for (SkuWareHasStock hasStock : collect){
            Long skuId = hasStock.getSkuId();
            Boolean skuStocked = false;
            List<Long> wareIdList = hasStock.getWareId();
            if (CollectionUtils.isEmpty(wareIdList)){
                throw new NoStockException(skuId);
            }

            // 如果每一个商品都锁定成功，将当前商品的库存锁定工作单记录发送给MQ
            // 锁定失败：前面保存的工作单信息被回滚了。
            for (Long wareId : wareIdList) {
                Long count = wareSkuDao.lockSkuStock(skuId, wareId, hasStock.getNum());
                if (count > 0){
                    // 保存订单锁定详情到数据库
                    WareOrderTaskDetailEntity wareOrderTaskDetailEntity = new WareOrderTaskDetailEntity();
                    wareOrderTaskDetailEntity.setSkuId(skuId);
                    wareOrderTaskDetailEntity.setSkuName("");
                    wareOrderTaskDetailEntity.setSkuNum(hasStock.getNum());
                    wareOrderTaskDetailEntity.setTaskId(wareOrderTaskEntity.getId());
                    wareOrderTaskDetailEntity.setWareId(wareId);
                    wareOrderTaskDetailEntity.setLockStatus(1);
                    wareOrderTaskDetailService.save(wareOrderTaskDetailEntity);

                    // 发送库存锁定成功
                    StockLockedTO stockLockedTO = new StockLockedTO();
                    stockLockedTO.setId(wareOrderTaskEntity.getId());
                    StockLockedDetail stockLockedDetail = new StockLockedDetail();
                    BeanUtils.copyProperties(wareOrderTaskDetailEntity, stockLockedDetail);
                    stockLockedTO.setDetail(stockLockedDetail);
                    rabbitTemplate.convertAndSend("stock-event-exchange", "stock.locked", stockLockedTO);
                    skuStocked = true;
                    break;
                }
            }
            if (false == skuStocked){
                throw new NoStockException(skuId);
            }
        }

        return true;
    }

    /**
     * 处理MQ消息，用于两种库存自动解锁情况
     * 1、下订单成功，库存锁定成功，但后面的业务失败，导致订单回滚。此时，被该订单锁定的库存需要被回滚
     * 2、锁库存时就失败
     * @param to
     */
    @Override
    public void unlockStock(StockLockedTO to) {
        System.out.println("收到解锁库存的消息");
        Long id = to.getId();
        StockLockedDetail detail = to.getDetail();
        Long detailId = detail.getId();

        // 查询数据库关于这个订单的锁定库存信息，如果没有则表示之前的锁定库存就失败了，库存回滚了，此时无需解锁
        WareOrderTaskDetailEntity byId = wareOrderTaskDetailService.getById(detailId);
        if (null != byId) {
            //需要解锁
            WareOrderTaskEntity taskEntity = wareOrderTaskService.getById(id);
            String orderSn = taskEntity.getOrderSn();
            R orderStatus = orderFeignService.getOrderStatus(orderSn);
            if (0 == orderStatus.getCode()) {
                // 订单数据返回成功
                OrderVO order = orderStatus.getData(new TypeReference<OrderVO>() {
                });

                if (null == order || 4 == order.getStatus() && 1 == byId.getLockStatus()) {
                    // 订单不能存在或者被取消，才能解锁库存
                    unLockStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum(), detailId);

                }
            }
        }
    }

    @Override
    public void unlockStock(OrderTo orderTo) {

        String orderSn = orderTo.getOrderSn();
        WareOrderTaskEntity wareOrderTaskEntity = wareOrderTaskService.getOrderTaskByOrderSn(orderSn);
        Long taskEntityId = wareOrderTaskEntity.getId();
        // 按照工作单找到所有没有解锁的库存，进行解锁
        List<WareOrderTaskDetailEntity> list = wareOrderTaskDetailService.list(new QueryWrapper<WareOrderTaskDetailEntity>()
                .eq("task_id", taskEntityId)
                .eq("lock_status", 1));
        for (WareOrderTaskDetailEntity wareOrderTaskDetailEntity : list) {
            unLockStock(wareOrderTaskDetailEntity.getSkuId(), wareOrderTaskDetailEntity.getSkuId(), wareOrderTaskDetailEntity.getSkuNum(), wareOrderTaskDetailEntity.getId());
        }
    }

    @Data
    class SkuWareHasStock{
        private Long skuId;
        private Integer num;
        private List<Long> wareId;
    }

}